#include"NewtonPoly.h"
#include<fstream>
#include<string>

/**
 * @brief 将区间[0,28]给280等分,取样本点,导出它们以及插值多项式在对应样本点处的值
 * 
 * 每次输出281组坐标,导出到`ProblemE_data/file?.txt`中(?=1,2).
 */
void plot_nth_sp(const vector<double> &inter_pts,
                 const vector<vector<double>> &vals_of_pts,
                 int n)
{
    string filename = "ProblemE_data/file" + to_string(n) + ".txt";//创建文件名  
    ofstream outputFile(filename);  //创建文件流对象
    if(outputFile.is_open()){
        for(int i = 0; i <= 280; i++){
            double x = i / 10.0;//取样本点
            double y = Newton_poly_at_x(inter_pts, vals_of_pts[n-1], x);
                                //取插值多项式在该样本点处的值
            outputFile << x << " " << y << endl;//导出到txt文件中
        }
        outputFile.close(); //关闭文件  
        cout << "File " << filename << " created and written successfully.\n";
    }
    else{  
        cout << "Error creating file: " << filename << endl;  
    }
}

/**
 * @brief 将区间[0,43]给430等分,取样本点,导出它们以及插值多项式在对应样本点处的值
 * 
 * 每次输出431组坐标,导出到`ProblemE_data/file?_predict.txt`中(?=1,2).
 */
void perdict_nth_sp(const vector<double> &inter_pts,
                    const vector<vector<double>> &vals_of_pts,
                    int n)
{
    /*判断幼虫是否死亡(即`vals_of_pts[n-1]`数组里的元素是否有非正数),若是,返回true.*/
    bool judge = false;

    string filename = "ProblemE_data/file" + to_string(n) + "_predict.txt";
                                    //创建文件名  
    ofstream outputFile(filename);  //创建文件流对象
    if(outputFile.is_open()){
        for(int i = 0; i <= 430; i++){
            double x = i / 10.0;    //取样本点
            double y = Newton_poly_at_x(inter_pts, vals_of_pts[n-1], x);
                                    //取插值多项式在该样本点处的值
            if(y <= 0){
                if(!judge){
                    cout << "在第" << i/10 << "天时,样本" << n << "的幼虫已死亡";
                    cout << endl;
                }              
                judge = true;
            }
            if(!judge && i==430)
                cout <<"再经过15天后,样本" << n << "的幼虫未死亡" << endl;
            if(i == 430)
                cout << "根据插值多项式,预测第43天的幼虫平均重量为:" << y << endl;
            outputFile << x << " " << y << endl;//导出到txt文件中
        }
        outputFile.close(); //关闭文件  
        cout << "File " << filename << " created and written successfully.\n";
    }
    else{  
        cout << "Error creating file: " << filename << endl;  
    }
}

int main(){
    vector<double> day = {0, 6, 10, 13, 17, 20, 28};
    vector<vector<double>> sp = {
        {6.67, 17.3, 42.7, 37.3, 30.1, 29.3, 28.7},
        {6.67, 16.1, 18.9, 15.0, 10.6, 9.44, 8.89},
    };
    for(int i = 1; i <= 2; i++){
        plot_nth_sp(day, sp, i);
        perdict_nth_sp(day, sp, i);
    }

    return 0;
}